package com.uvnos4j.matilda.system.controller;

import com.uvnos4j.matilda.commons.annotation.AppLog;
import com.uvnos4j.matilda.commons.dto.QueryParam;
import com.uvnos4j.matilda.commons.dto.Result;
import com.uvnos4j.matilda.commons.utils.RequestUtil;
import com.uvnos4j.matilda.commons.utils.TreeUtil;
import com.uvnos4j.matilda.system.domain.SysDept;
import com.uvnos4j.matilda.system.service.SysDeptService;
import com.uvnos4j.matilda.system.vo.DeptVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 部门 Controller
 * <p>
 * Description:部门 Controller
 * </p>
 *
 * @author Guo.wl
 * @version v1.0.0
 * @see com.uvnos4j.matilda.system.controller
 * @since 2020-08-31 23:13:25
 */
@Controller
@RequestMapping("/sys/dept")
public class SysDeptController {

    @Autowired
    private SysDeptService sysDeptService;

    @AppLog(title = "部门管理")
    @PreAuthorize("hasAuthority('sys:dept')")
    @GetMapping("/list")
    public String index() {
        return "sys/deptlist";
    }

    @PreAuthorize("hasAuthority('sys:dept')")
    @ResponseBody
    @GetMapping
    public Result tree() {
        QueryParam param = RequestUtil.getQueryParam();
        List<SysDept> deptList = sysDeptService.list(param);
        List<SysDept> treeList = TreeUtil.bulidTree(deptList);
        return Result.success(treeList);
    }

    @AppLog(title = "添加部门")
    @PreAuthorize("hasAuthority('sys:dept:add')")
    @ResponseBody
    @PostMapping
    public Result add(@Valid DeptVo vo) {
        SysDept dept = vo.buildModel(SysDept.class, false);
        sysDeptService.save(dept);
        return Result.success("部门添加成功", dept.getId());
    }

    @AppLog(title = "修改部门")
    @PreAuthorize("hasAuthority('sys:dept:update')")
    @ResponseBody
    @PutMapping
    public Result update(@Valid DeptVo vo) {
        SysDept dept = vo.buildModel(SysDept.class, true);
        sysDeptService.updateById(dept);
        return Result.success("部门修改成功", dept.getId());
    }

    @AppLog(title = "删除部门")
    @PreAuthorize("hasAuthority('sys:dept:del')")
    @ResponseBody
    @DeleteMapping
    public Result delete(@RequestParam("ids") List<String> idList) {
        boolean b = sysDeptService.removeByIds(idList);
        if (b) {
            return Result.success("部门删除成功");
        }
        return Result.fail("部门删除失败");
    }

}